package org.huangrui.javase.io;

import org.huangrui.entities.Student;
import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

/**
 * @Author hr
 * @Create 2025-11-08 0:00
 **/
public class T02StudentSerialize {
    @Test
    public void test1(){
        Student student = new Student("谷姐", 100);
        try(
                FileOutputStream fos = new FileOutputStream("student.obj");
                ObjectOutputStream oos = new ObjectOutputStream(fos);
        ){
            oos.writeObject(student);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test2(){
        try(
                FileInputStream fis = new FileInputStream("student.obj");
                ObjectInputStream ois = new ObjectInputStream(fis);
        ){
            Object stu = ois.readObject();
            System.out.println(stu);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test3()throws Exception{
        Student student1 = new Student("谷姐", 100);
        Student student2 = new Student("谷妹", 99);
        Student student3 = new Student("谷哥", 98);
        Student student4 = new Student("谷弟", 97);

        ArrayList<Student> list = new ArrayList<>();
        list.add(student1);
        list.add(student2);
        list.add(student3);
        list.add(student4);

        try(
                FileOutputStream fos = new FileOutputStream("students.obj");
                ObjectOutputStream oos = new ObjectOutputStream(fos);
        ){
            oos.writeObject(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test4(){
        try(
                FileInputStream fis = new FileInputStream("students.obj");
                ObjectInputStream ois = new ObjectInputStream(fis);
        ){
            ArrayList<Student> list = (ArrayList<Student>) ois.readObject();
            list.forEach(System.out::println);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
